<template>
  <div class="apply-shop-container">
    <div class="page-header">
      <h1>商家入驻申请</h1>
      <p>加入匠心电商平台，让您的商品触达更多消费者</p>
    </div>

    <el-card class="apply-form-card">
      <template #header>
        <div class="form-header">
          <h2>填写入驻信息</h2>
          <p>请认真填写以下信息，我们将在1-3个工作日内审核</p>
        </div>
      </template>
      
      <el-form 
        ref="shopFormRef" 
        :model="shopForm" 
        :rules="shopRules" 
        label-position="top"
        status-icon
      >
        <!-- 店铺基本信息 -->
        <h3 class="section-title">店铺基本信息</h3>
        
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="shopForm.name" placeholder="请输入店铺名称" />
        </el-form-item>
        
        <el-form-item label="店铺简介" prop="description">
          <el-input 
            v-model="shopForm.description" 
            type="textarea" 
            rows="3"
            placeholder="请简要描述您的店铺经营理念和特色" 
          />
        </el-form-item>
        
        <el-form-item label="经营类目" prop="category">
          <el-select 
            v-model="shopForm.category" 
            placeholder="请选择主要经营类目"
            style="width: 100%"
          >
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="店铺LOGO" prop="logo">
          <el-upload
            class="logo-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="shopForm.logo" :src="shopForm.logo" class="logo-image" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传正方形图片，大小不超过2MB</div>
        </el-form-item>
        
        <!-- 经营者信息 -->
        <h3 class="section-title">经营者信息</h3>
        
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="shopForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="shopForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="电子邮箱" prop="contactEmail">
          <el-input v-model="shopForm.contactEmail" placeholder="请输入电子邮箱" />
        </el-form-item>
        
        <!-- 资质信息 -->
        <h3 class="section-title">资质信息</h3>
        
        <el-form-item label="营业执照" prop="businessLicense">
          <el-upload
            class="license-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleLicenseSuccess"
            :before-upload="beforeLicenseUpload"
          >
            <img v-if="shopForm.businessLicense" :src="shopForm.businessLicense" class="license-image" />
            <div v-else class="license-uploader-box">
              <el-icon class="license-uploader-icon"><Plus /></el-icon>
              <div>点击上传营业执照</div>
            </div>
          </el-upload>
          <div class="upload-tip">请上传清晰的营业执照照片或扫描件，格式为JPG或PNG</div>
        </el-form-item>
        
        <el-form-item label="经营范围" prop="businessScope">
          <el-input 
            v-model="shopForm.businessScope" 
            type="textarea" 
            rows="3"
            placeholder="请输入营业执照上的经营范围" 
          />
        </el-form-item>
        
        <el-form-item label="入驻协议" prop="agreement">
          <el-checkbox v-model="shopForm.agreement">
            我已阅读并同意<a href="#" @click.prevent="showAgreement">《匠心电商平台入驻协议》</a>
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="submitting" 
            @click="submitApplication"
            style="width: 100%"
          >
            提交申请
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 协议对话框 -->
    <el-dialog
      v-model="agreementDialogVisible"
      title="匠心电商平台入驻协议"
      width="70%"
    >
      <div class="agreement-content">
        <h3>匠心电商平台入驻协议</h3>
        <p>欢迎您申请入驻匠心电商平台！请仔细阅读以下协议内容：</p>
        
        <h4>一、入驻条件</h4>
        <p>1. 申请人须具有合法的经营资质，包括但不限于营业执照、税务登记证等。</p>
        <p>2. 申请人提供的所有资料必须真实、有效、合法。</p>
        <p>3. 申请人的经营范围必须符合国家法律法规和平台规定。</p>
        
        <h4>二、商家责任</h4>
        <p>1. 商家应确保在平台上销售的商品质量符合国家标准。</p>
        <p>2. 商家应按照承诺及时发货并提供售后服务。</p>
        <p>3. 商家应遵守平台的各项规则和政策。</p>
        
        <h4>三、平台服务</h4>
        <p>1. 平台为商家提供网络交易平台服务。</p>
        <p>2. 平台有权对商家的经营行为进行监督和管理。</p>
        <p>3. 平台将收取一定比例的服务费用，具体费率以合作协议为准。</p>
        
        <h4>四、违约责任</h4>
        <p>1. 如商家违反本协议或平台规则，平台有权采取警告、限制经营、终止合作等措施。</p>
        <p>2. 因商家原因造成消费者或平台损失的，商家应承担相应的赔偿责任。</p>
        
        <h4>五、协议期限</h4>
        <p>本协议自商家入驻申请通过之日起生效，有效期为一年。期满后如双方无异议，自动续期。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="agreementDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="agreeToTerms">
            同意协议
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { applyShop } from '@/api/shop' // 假设有这个API

const router = useRouter()
const shopFormRef = ref(null)
const submitting = ref(false)
const agreementDialogVisible = ref(false)

// 店铺表单数据
const shopForm = reactive({
  name: '',
  description: '',
  category: '',
  logo: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  businessLicense: '',
  businessScope: '',
  agreement: false
})

// 表单验证规则
const shopRules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入店铺简介', trigger: 'blur' },
    { min: 10, max: 200, message: '长度在10到200个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择经营类目', trigger: 'change' }
  ],
  logo: [
    { required: true, message: '请上传店铺LOGO', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  businessScope: [
    { required: true, message: '请输入经营范围', trigger: 'blur' }
  ],
  agreement: [
    { validator: (rule, value, callback) => {
      if (value === false) {
        callback(new Error('请阅读并同意入驻协议'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ]
}

// 经营类目选项
const categoryOptions = [
  { value: 'electronics', label: '电子产品' },
  { value: 'clothing', label: '服装鞋包' },
  { value: 'food', label: '食品生鲜' },
  { value: 'home', label: '家居家装' },
  { value: 'beauty', label: '美妆个护' },
  { value: 'mother', label: '母婴用品' },
  { value: 'sports', label: '运动户外' },
  { value: 'books', label: '图书音像' },
  { value: 'other', label: '其他' }
]

// 上传LOGO相关方法
const handleLogoSuccess = (res, file) => {
  // 假设上传成功后返回图片URL
  shopForm.logo = res.url || URL.createObjectURL(file.raw)
}

const beforeLogoUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('LOGO只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('LOGO大小不能超过2MB!')
    return false
  }
  return true
}

// 上传营业执照相关方法
const handleLicenseSuccess = (res, file) => {
  // 假设上传成功后返回图片URL
  shopForm.businessLicense = res.url || URL.createObjectURL(file.raw)
}

const beforeLicenseUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('营业执照只能是JPG或PNG格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('营业执照大小不能超过5MB!')
    return false
  }
  return true
}

// 显示协议对话框
const showAgreement = () => {
  agreementDialogVisible.value = true
}

// 同意协议
const agreeToTerms = () => {
  shopForm.agreement = true
  agreementDialogVisible.value = false
}

// 提交申请
const submitApplication = async () => {
  if (!shopFormRef.value) return
  
  try {
    await shopFormRef.value.validate()
    
    submitting.value = true
    
    // 调用申请入驻API
    try {
      // 这里假设有一个applyShop的API
      await applyShop(shopForm)
      
      ElMessageBox.alert(
        '您的入驻申请已提交成功，我们将在1-3个工作日内审核，请留意系统通知。',
        '申请提交成功',
        {
          confirmButtonText: '确定',
          callback: () => {
            router.push('/user')
          }
        }
      )
    } catch (error) {
      console.error('提交申请失败:', error)
      ElMessage.error(error.message || '提交失败，请稍后重试')
    } finally {
      submitting.value = false
    }
    
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  }
}
</script>

<style scoped>
.apply-shop-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.apply-form-card {
  margin-bottom: 40px;
}

.form-header {
  text-align: center;
}

.form-header h2 {
  font-size: 20px;
  margin-bottom: 5px;
}

.form-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.section-title {
  margin-top: 30px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
  font-size: 18px;
}

.logo-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.logo-uploader:hover {
  border-color: #409EFF;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.logo-image {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.license-uploader {
  width: 100%;
  height: 180px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.license-uploader:hover {
  border-color: #409EFF;
}

.license-uploader-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.license-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.license-image {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.agreement-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 0 20px;
}

.agreement-content h3 {
  text-align: center;
}

.agreement-content h4 {
  margin-top: 20px;
  margin-bottom: 10px;
}

.agreement-content p {
  margin: 10px 0;
  line-height: 1.6;
}
</style> 